package com.jack.lib.test.view

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.view.LayoutInflater
import android.view.MotionEvent
import android.widget.FrameLayout
import com.jack.lib.core.ext.trues
import com.jack.lib.test.databinding.ViewGlobalBinding
import kotlin.math.absoluteValue

/**
 * author : chong.huang
 * create : 2022/2/4
 * desc   :
 */
class GlobalView(context: Context) : FrameLayout(context) {

    private val binding by lazy { ViewGlobalBinding.inflate(LayoutInflater.from(context), this, true) }
    private var moveX: Float = 0F
    private var moveY: Float = 0F
    var onDrag: ((dx: Float, dy: Float) -> Unit)? = null

    init {
        binding.debug.setOnClickListener {
            context.startActivity(Intent(context, TestMainActivity::class.java).apply {
                flags = Intent.FLAG_ACTIVITY_NEW_TASK
            })
        }
    }

    override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                moveX = event.rawX
                moveY = event.rawY
            }
            MotionEvent.ACTION_MOVE -> ((event.rawX - moveX).absoluteValue > 8 || (event.rawY - moveY).absoluteValue > 8).trues { return true }
        }
        return super.onInterceptTouchEvent(event)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (event.action == MotionEvent.ACTION_MOVE) {
            val dx = event.rawX - moveX
            val dy = event.rawY - moveY

            moveX = event.rawX
            moveY = event.rawY

            onDrag?.invoke(dx, dy)
        }
        return true
    }
}